/*
 * Copyright 2010 Christopher Z. Collier
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.xorf.caveman.gui;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 * A modification of <tt>JTable</tt> to encapsulate
 * managing a <tt>DefaultTableModel</tt> for very
 * simple <tt>JTable</tt> needs.
 * 
 * Setting the <tt>columnNames</tt> property defines
 * columns in the model, and rows consisting of Object
 * arrays of the same cardinality of <tt>columnNames</tt>
 * can be added directly through the table, rather than
 * having to deal with a separate <tt>TableModel</tt>
 * externally.
 * 
 * @author ccollier
 */
@SuppressWarnings({ "serial" })
public class EasyJTable extends JTable {
    private String[] columnNames;
    private DefaultTableModel model = new DefaultTableModel();
    
    public EasyJTable() {
        setModel(model);
    }
    
    public EasyJTable(String[] colNames) {
        setColumnNames(colNames);
    }
    
    public void setColumnNames(String[] columnNames) {
        this.columnNames = columnNames;
        for (String colName : columnNames) {
            model.addColumn(colName);
        }
    }
    
    public void addRow(Object[] data) {
        if (data.length != columnNames.length)
            throw new IllegalArgumentException(String.format(
                    "number of fields in data (%s) does not match number of columns in table(%s)",
                    data.length, columnNames.length));

        model.addRow(data);
    }
    
    public void setData(Object[][] data) {
        model.setDataVector(data, columnNames);
    }
}
